package com.bakery.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.bakery.entity.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * Sa-Token配置类
 *
 * @author bakery
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {
    
    /**
     * 注册Sa-Token拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handle -> {
            // 排除登录接口
            SaRouter.match("/**")
                    .notMatch("/employee/login")
                    .check(r -> StpUtil.checkLogin());
        })).addPathPatterns("/**");
    }
    
    /**
     * 权限认证接口实现
     */
    @Bean
    public StpInterface stpInterface() {
        return new StpInterface() {
            
            /**
             * 返回指定账号id所拥有的权限码集合
             */
            @Override
            public List<String> getPermissionList(Object loginId, String loginType) {
                // 本系统暂不使用权限码，返回空集合
                return new ArrayList<>();
            }
            
            /**
             * 返回指定账号id所拥有的角色标识集合
             */
            @Override
            public List<String> getRoleList(Object loginId, String loginType) {
                List<String> roles = new ArrayList<>();
                
                // 从Session中获取员工信息
                Employee employee = (Employee) StpUtil.getSession().get("employee");
                if (employee != null) {
                    roles.add(employee.getRole());
                }
                
                return roles;
            }
        };
    }
}

